import {
	setStorage,
	getStorage,
	removeStorage
} from "@/util/auth";
import { getLoginApi,logoutApi} from "@/api/user.js";
const state = {
	token: getStorage('token')
}
const mutations = {
	SET_TOKEN(state, token) {
		if (token === null) {
			removeStorage('token');
		} else {
			setStorage('token', token, 15*24*60)
		}
		state.token = token;
		uni.$emit('tokenChange',token)
	},
}
const actions = {
	handleLogin({
		commit
	}, form) {
		return new Promise((resolve, reject) => {
			getLoginApi(form).then((res) => {
				commit('SET_TOKEN', res.token);
				resolve();
			}).catch(() => {
				reject();
			})
		})
	},
	logout({commit}){
		return new Promise(async (resolve, reject) => {
			commit('SET_TOKEN', null);
			commit('push/SET_ONLINE', false,{root:true});
			commit('push/SET_READY', false,{root:true});
			await logoutApi()
			resolve();
		})
	}
}
export default {
	namespaced: true,
	state,
	mutations,
	actions
}
